import { Injectable } from '@angular/core';
import { Observable } from "rxjs";
// import {observable} from "rxjs/symbol/observable";
@Injectable()
export class WebSocketService {

  ws: WebSocket

  constructor() {

  }
  /**
   * 
   * @param url 创建socket连接
   * @returns 
   */
  createObservableSocket(url: string): Observable<any> {
    this.ws = new WebSocket(url);
    var that = this;
    /**
     * 轮询心跳
     */
    window.setInterval(function () {
      var ping = "1|ping";
      that.sendMessage(ping);
    }, 5000);
    return new Observable<any>(
      observable => {
        this.ws.onmessage = (event) => observable.next("message----" + event.data);
        this.ws.onerror = (event) => observable.error(event);
        this.ws.onclose = (event) => observable.complete();
        this.ws.onopen = (event) => observable.next("open----")
      }
    )
  }
  sendMessage(message: string) {
    this.ws.send(message);
  }
}
class openmessage {
  constructor() {

  }
}